
package com.TangoGames.panel;

import java.util.Collection;
import java.util.Map;

import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;


/**
 * 
 * @author Arthur
 *
 */
public class BaseThread extends Thread
{
	/**
	 * 
	 */
	private static final String TAG = BaseThread.class.getSimpleName();
		
	/**
	 * 
	 */
	private BasePanel panel;

	/**
	 * 
	 */
	SurfaceHolder surfaceholder;
	
	/**
	 * 
	 */
	private boolean running;
	
	/**
	 * 
	 */
	private long gameTime;
	
	/**
	 * 
	 * @param running
	 */
	public void setRunning(boolean running)
	{		
		this.running = running;
	}

	/**
	 * 
	 * @param surfaceHolder
	 * @param gamePanel
	 */
	public BaseThread(BasePanel panel)
	{
		//
		super();
		
		//
		this.panel = panel;
		
		//
		surfaceholder = this.panel.getHolder();
		
	}

	/**
	 * 
	 */
	@Override
	public void run()
	{
		//
		Canvas canvas;
		
		//
		while (running)
		{
			//
			canvas = null;
			
			//
			try
			{
				//
				canvas = surfaceholder.lockCanvas();
				
				if (canvas !=null)
				{ 						
				//
					synchronized (surfaceholder)
					{
						gameTime = System.currentTimeMillis();
						//
						this.panel.getCurrentPanel().Update(gameTime);
						//
						if (this.panel.getCurrentPanel().getChildrenElements() != null) callUpdateChildElements(this.panel.getCurrentPanel().getChildrenElements());
						//
						this.panel.getCurrentPanel().Draw(canvas);
						//
						if (this.panel.getCurrentPanel().getChildrenElements() != null) callDrawChildElements(this.panel.getCurrentPanel().getChildrenElements(), canvas);
						
					}
				}
			}
			//
			finally
			{
				
				if (canvas != null)
				{
					surfaceholder.unlockCanvasAndPost(canvas);
				}
			}
		}
	}


	
	/**
	 * Call all of children updates
	 * @param childrenElements
	 */
	private void callUpdateChildElements( Collection<IPanelElement> childrenElements) {
		if (!childrenElements.isEmpty()) {  
			for ( IPanelElement entry : childrenElements ) {
				entry.Update(gameTime);
				if (entry.getChildrenElements() != null) callUpdateChildElements(entry.getChildrenElements());
			} 
		}
	}

	/**
	 * Call all of children Draw
	 * @param childrenElements
	 * @param canvas
	 */
	private void callDrawChildElements( Collection<IPanelElement> childrenElements, Canvas canvas) {
		if (!childrenElements.isEmpty()) { 	
			for ( IPanelElement entry : childrenElements ) { 
				if (entry.isDrawable()) entry.Draw(canvas);
				if (entry.getChildrenElements() != null) callDrawChildElements(entry.getChildrenElements(), canvas);				
			}
		}		
	}

}
